import CryptoJS from 'crypto-js';

const MD5_TABLE = '0123456789abcdef';

function md5(cipherText) {
  try {
    const md = CryptoJS.MD5(cipherText).toString(CryptoJS.enc.Hex);
    return md;
  } catch (error) {
    console.error('md5 函数出错:', error);
    return null;
  }
}

function hmacSHA1Encrypt(encryptText, encryptKey) {
  try {
    const key = CryptoJS.enc.Utf8.parse(encryptKey);
    const text = CryptoJS.enc.Utf8.parse(encryptText);
    const hmac = CryptoJS.HmacSHA1(text, key);
    const result = CryptoJS.enc.Base64.stringify(hmac);
    return result;
  } catch (error) {
    console.error('hmacSHA1Encrypt 函数出错:', error);
    return null;
  }
}

export function getSignature(appId, secret, ts) {
  try {
    const auth = md5(appId + ts);
    return hmacSHA1Encrypt(auth, secret);
  } catch (error) {
    console.error('getSignature 函数出错:', error);
    return null;
  }
}